@extends('common.admin_template')

@section('content')
    <div class="boxWidth">
        @include('common.notice_msg')
        <form id="service" method="post" action="{{url('admin/coupons/save')}}">
            <input type="hidden" name="_token" value="{{ csrf_token() }}">
            <input type="hidden" name="Post[id]" id="id" value="{{ isset($Post)?$Post->id:"" }}">
            <input type="hidden" name="Post[content]" id="PostContent">
            <input type="hidden" name="Post[arr]" id="PostTagArr">
            <input type="hidden" name="Post[fy]" id="fy" value="{{ isset($meta)&&isset($meta["fy"])?$meta["fy"]:"" }}">
            <input type="hidden" name="Post[user_id]" value="{{ isset($Post)?$Post->user_id:$CurrentUser->id }}">
            <div class="row">
                <div class="col-xs-9 boxPaddingLeft">
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>标题</span><i class="glyphicon icon-arrow-left"></i></div>
                        <div class="col-xs-11" id="titleNameBox"><input type="text" class="form-control" id="titleName" name="Post[title]" placeholder="请输入标题" value="{{ isset($Post)?$Post->title:'' }}"></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>作者</span></div>
                        <div class="col-xs-11" id="authorNameBox"><input type="text" class="form-control" id="authorName" name="Post[author]" placeholder="请输入作者名称" value="{{ isset($Post)?$Post->author:$CurrentUser->name }}"></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>时间</span></div>
                        <div class="row col-xs-11 postItemValue">
                            <div class="row"><div class="col-xs-6">开始时间</div><div class="col-xs-6">结束时间</div></div>
                            <div class="row">
                                <div class="col-xs-6" id="startCouponBox"><input type="text" id="startCoupon" readonly class="form-control form_datetime" name="Post[startCoupon]" value=""></div>
                                <div class="col-xs-6" id="endCouponBox"><input type="text" id="endCoupon" readonly class="form-control form_datetime" name="Post[endCoupon]" value=""></div>
                            </div>
                        </div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>类型</span></div>
                        <div class="col-xs-1 postItemName">
                            <select name="Post[tag]" id="postTag">
                                @foreach($services as $s)
                                    <option value="{{$s->id}}">{{$s->name}}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-xs-10" id="coupon_tag">
                            <div id="coupon_discountBox"><input type="text" class="form-control" id="coupon_discount" name="Post[coupon_discount]" placeholder="请输入折扣比例（0-99），0为全额抵扣" value="{{ isset($meta)&&isset($meta["coupon_discount"])?$meta["coupon_discount"]:'' }}"></div>
                        </div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>对象</span></div>
                        <div class="col-xs-1 postItemName">
                            <select name="Post[coupon_type]" id="coupon_type">
                                <option value="all">全场通用</option>
                                <option value="shop">商铺</option>
                                <option value="service">服务</option>
                            </select>
                        </div>
                        <div class="col-xs-10" id="coupon_idBox"><input type="text" class="form-control" id="coupon_id" name="Post[coupon_id]" placeholder="请输入对应服务或商铺的ID（访问链接最后的数字编号），填写0为全场通用" value="{{ isset($meta)&&isset($meta["coupon_id"])?$meta["coupon_id"]:'' }}"></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>数量</span></div>
                        <div class="col-xs-11" id="coupon_numBox"><input type="text" class="form-control" id="coupon_num" name="Post[coupon_num]" placeholder="请输入优惠券数量" value="{{ isset($meta)&&isset($meta["coupon_num"])?$meta["coupon_num"]:'' }}"></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>限制</span></div>
                        <div class="col-xs-11" id="coupon_limitBox"><input type="text" class="form-control" id="coupon_limit" name="Post[coupon_limit]" placeholder="请输入单个用户限制领取次数，填0则不限制领取次数" value="{{ isset($meta)&&isset($meta["coupon_limit"])?$meta["coupon_limit"]:'' }}"></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>等级</span></div>
                        <div class="col-xs-10"><input type="text" class="form-control" name="Post[coupon_level]" placeholder="可领取用户的等级，多个以空隔开，如2 4 5，不填则没有限制。勾选右边按钮需要申请才能领取。" value="{{ isset($meta)&&isset($meta["coupon_level"])?$meta["coupon_level"]:'' }}"></div>
                        <div class="col-xs-1 postItemName qrCreate"><input type="checkbox" name="Post[coupon_form]" {{ isset($meta)&&isset($meta["coupon_form"])?'checked':'' }}></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>二维码</span></div>
                        <div class="col-xs-10" ><input type="text" class="form-control" name="Post[viewQR]" placeholder="小程序分享二维码，勾选右边按钮自动生成" value="{{ isset($meta)&&isset($meta["viewQR"])?$meta["viewQR"]:'' }}"></div>
                        <div class="col-xs-1 postItemName qrCreate"><input type="checkbox" name="Post[createQR]"></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-12">
                            <div class="postBox" contenteditable="true" id="PostContentBox">
                                {!! isset($Post)?$Post->content:''  !!}
                            </div>
                        </div>
                    </div>
                    <div id="postItemValueContainer">
                        <div class="row editFormItem">
                            <div class="col-xs-2 postItemName"><span>服务说明</span></div>
                            <div class="col-xs-6 activeItemBtn">
                                <span id="activeChange" style="display: block"><span class="redColor" id="delActive">删除</span><span id="addActive">添加</span></span>
                            </div>
                            <div class="col-xs-4" id="contentImg"><button><img src="{{asset('img/upload.png')}}">上传图片</button></div>
                        </div>
                        <div class="row editFormItem" id="postItemValueBox">
                            <div class="col-xs-2 postItemName"></div>
                            <div class="row col-xs-10 postItemValue" id="postItemValue">
                                <div class="row"><div class="col-xs-6">名称</div><div class="col-xs-6">值</div></div>
                                <div class="row">
                                    <div class="col-xs-6" id="activeKey_0Box"><input type="text" id="activeKey_0" class="form-control" name="Post[activeKey_0]" value=""></div>
                                    <div class="col-xs-6" id="activeValue_0Box"><input type="text" id="activeValue_0" class="form-control" name="Post[activeValue_0]" value=""></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-2 postItemName"><span>优惠券价格</span></div>
                        <div class="col-xs-10 activeItemBtn"><input type="text" class="form-control" name="Post[coupon_price]" placeholder="请输入优惠券购买价格，如不填则为免费领取" value="{{ isset($meta)&&isset($meta["coupon_price"])?$meta["coupon_price"]:'' }}"></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-2 postItemName"><span>商户优惠码金额</span></div>
                        <div class="col-xs-10 activeItemBtn"><input type="text" class="form-control" name="Post[coupon_code]" placeholder="请输入商户获取优惠码可抵扣的金额，如不填则不发放优惠码" value="{{ isset($meta)&&isset($meta["coupon_code"])?$meta["coupon_code"]:'' }}"></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-2 postItemName"><span>购买备注</span></div>
                        <div class="col-xs-10 activeItemBtn"><input type="text" class="form-control" name="Post[coupon_summary]" placeholder="请输入优惠券购买备注" value="{{ isset($meta)&&isset($meta["coupon_summary"])?$meta["coupon_summary"]:'' }}"></div>
                    </div>
                </div>
                <div class="col-xs-3 boxPaddingRight">
                    <div class="postBtnBox">
                        <div class="row postItem">
                            <div class="col-xs-3 postItemName"><span>状态</span></div>
                            <div class="col-xs-8">
                                <select name="Post[status]" id="postStatus">
                                    <option value="0">待审</option>
                                    <option value="1">通过</option>
                                </select>
                            </div>
                        </div>
                        <div class="row postItem">
                            <div class="col-xs-3 postItemName"><span>小程序</span></div>
                            <div class="col-xs-8">
                                <select name="Post[xcx]" id="postXcx">
                                    @foreach($xcxs as $xcx)
                                        @if($xcx->name=="优惠券")
                                            <option value="{{$xcx->id}}">{{$xcx->name}}</option>
                                        @endif
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        @if(isset($Post))
                        <div class="row postItem">
                            <div class="col-xs-3 postItemName"><span>时间</span></div>
                            <div class="col-xs-8"><input type="text" id="created_at" readonly name="Post[created_at]" value="">
                            </div>
                        </div>
                        @endif
                        <div id="filterBox">
                            <div class="row postItem">
                                <div class="col-xs-8 postItemName" id="filterName"><span>筛选名：</span></div>
                                <div class="col-xs-3"></div>
                            </div>
                            <div class="row postItem ">
                                <div class="col-xs-1"></div>
                                <div class="col-xs-9 postTagBox" id="filterGroup"></div>
                            </div>

                        </div>
                        <div class="row postItemBtn" >
                            <div class="col-xs-8"><button class="btn btn-primary" type="submit" id="formSubmit">发布</button></div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
@stop
@section('js')
    <script src="{{asset('js/bootstrap-datetimepicker.js')}}"></script>
    <script src="{{asset('js/plupload/plupload.full.min.js')}}"></script>
    <script src="{{asset('js/quill.js')}}"></script>
    <script>
        (function () {
            function getId(arr,num) {
                return arr.indexOf(Number(num));
            }
            function hasError(id){
                var str =  $('#'+id).val().replace(/(^\s*)|(\s*$)/g, "");
                if(!str){
                    $('#'+id+'Box').addClass('has-error');
                    return 1;
                }
                return 0;
            }
            function activeChange(value) {
                if(value!='no'){
                    $('#activeChange').show();
                    if(value==0){
                        $('#postItemValue').append(
                                '<div class="row">' +
                                '<div class="col-xs-6" id="activeKey_0Box"><input type="text" id="activeKey_0" class="form-control" name="Post[activeKey_0]"></div>' +
                                '<div class="col-xs-6" id="activeValue_0Box"><input type="text" id="activeValue_0" class="form-control" name="Post[activeValue_0]"></div>' +
                                '</div>');
                    }else if(value=="edit"){
                                @if(isset($meta)&&isset($meta["service"]))
                        {!!'var activeArr = '.$meta["service"]!!}
                        var arr="";
                        for(var k = 0;k<activeArr.key.length;k++){
                            arr +=  '<div class="row">' +
                                    '<div class="col-xs-6" id="activeKey_'+k+'Box"><input type="text" id="activeKey_'+k+'" class="form-control" name="Post[activeKey_'+k+']" value="'+activeArr.key[k]+'"></div>' +
                                    '<div class="col-xs-6" id="activeValue_'+k+'Box"><input type="text" id="activeValue_'+k+'" class="form-control" name="Post[activeValue_'+k+']" value="'+activeArr.value[k]+'"></div>' +
                                    '</div>';
                        }
                        $('#postItemValue').append(arr);
                        @endif
                    }else{
                        var idx = getId(formId,value);
                        if(idx != -1){
                            for(var i=0;i<formArr[idx].item.length;i++){
                                var num = $('#postItemValue .row').length - 1;
                                $('#postItemValue').append(
                                        '<div class="row">' +
                                        '<div class="col-xs-6" id="activeKey_'+num+'Box"><input type="text" id="activeKey_'+num+'" class="form-control" name="Post[activeKey_'+num+']" value="'+formArr[idx].item[i]+'"></div>' +
                                        '<div class="col-xs-6" id="activeValue_'+num+'Box"><input type="text" id="activeValue_'+num+'" class="form-control" name="Post[activeValue_'+num+']"></div>' +
                                        '</div>');

                            }
                        }
                    }
                }else{
                    $('#activeChange').hide();
                }
            }
            function getToken() {
                $.ajax({
                    url: '{{asset("qiniu.php")}}',
                    type: "get",
                    success: function (response) {
                        token = response;
                        if(!tokenTime){
                            uploader.init();
                        }
                        tokenTime = Math.round(new Date().getTime()/1000);
                    },
                    error: function () {
                        alert('加载失败')
                    },
                    complete: function () {}
                });
            }
            function upInit() {
                if(Math.round(new Date().getTime()/1000)>(tokenTime+3500)){getToken()}
            }
            function selectFilter(index) {
                var i = filter.tag.indexOf(Number(index)),
                    box = $('#filterBox');
                $('#filterGroup').html('');
                if(filter.id[i].length){
                    box.show();
                    $('#filterName').html("<span>筛选名："+filter.filterName[i]+"<span>");
                    for(var k=0;k<filter.id[i].length;k++){
                    @if(isset($tagGroup))
                        $('#filterGroup').append('<div class="row"><input class="postTagInput" type="checkbox" value="'+filter.id[i][k]+'"'+(group.indexOf(filter.id[i][k])!==-1?"checked":"")+'><div class="postTagName">'+filter.name[i][k]+'</div></div>');
                    @else
                        $('#filterGroup').append('<div class="row"><input class="postTagInput" type="checkbox" value="'+filter.id[i][k]+'"><div class="postTagName">'+filter.name[i][k]+'</div></div>');
                    @endif
                    }
                }else{
                    box.hide();
                }

            }
            function changeTag() {
                var postTag = $("#postTag");
                if(postTag.find("option:selected").text()==='折扣券'){
                    $('#coupon_tag').html('<div id="coupon_discountBox"><input type="text" class="form-control" id="coupon_discount" name="Post[coupon_discount]" placeholder="请输入折扣比例（0-99），0为全额抵扣" value="{{ isset($meta)&&isset($meta["coupon_discount"])?$meta["coupon_discount"]:'' }}"></div>')
                }else if(postTag.find("option:selected").text()==='代金券'){
                    $('#coupon_tag').html('<div id="coupon_cashBox"><input type="text" class="form-control" id="coupon_cash" name="Post[coupon_cash]" placeholder="请输入代金券面额" value="{{ isset($meta)&&isset($meta["coupon_cash"])?$meta["coupon_cash"]:'' }}"></div>')
                }else{
                    $('#coupon_tag').html('<div id="coupon_fullBox" class="col-xs-6"><input type="text" class="form-control" id="coupon_full" name="Post[coupon_full]" placeholder="请输入需达到满减的金额" value="{{ isset($meta)&&isset($meta["coupon_full"])?$meta["coupon_full"]:'' }}"></div><div id="coupon_cutBox" class="col-xs-6"><input type="text" class="form-control" id="coupon_cut" name="Post[coupon_cut]" placeholder="请输入满减优惠的金额" value="{{ isset($meta)&&isset($meta["coupon_cut"])?$meta["coupon_cut"]:'' }}"></div>')
                }
            }

            var token,tokenTime;
            var id = function(id) {return document.getElementById(id);};
            var editor = new Quill('#PostContentBox', {
                modules: {
                    toolbar: [
                        [{ header: [1, 2, 3, 4, 5, 6, false] }],
                        ['bold', 'italic', 'underline', 'strike', { 'align': [] }],
                        [{ 'color': [] }, { 'background': [] }],
                        [{ 'indent': '-1'}, { 'indent': '+1' }, { 'list': 'bullet' }]
                    ] },
                theme: 'snow'
            });
            var Align = Quill.import('attributors/style/align');
            Align.whitelist = ['right', 'center', 'justify'];
            Quill.register(Align, true);

            var picName = new Date();
            var upType;
            picName = picName.getFullYear().toString()+((picName.getMonth()+1)<10?'0'+(picName.getMonth()+1):(picName.getMonth()+1))+(picName.getDate()<10?'0'+picName.getDate():picName.getDate().toString())+'_'+(picName.getHours()<10?'0'+picName.getHours():picName.getHours().toString())+(picName.getMinutes()<10?'0'+picName.getMinutes():picName.getMinutes().toString())+(picName.getSeconds()<10?'0'+picName.getSeconds():picName.getSeconds().toString());

            $(".form_datetime").datetimepicker({format: 'yyyy-mm-dd',minView:2});
            $('#addActive').on('click',function () {
                var num = $('#postItemValue .row').length - 1;
                $('#postItemValue').append(
                        '<div class="row">' +
                        '<div class="col-xs-6" id="activeKey_'+num+'Box"><input type="text" id="activeKey_'+num+'" class="form-control" name="Post[activeKey_'+num+']"></div>' +
                        '<div class="col-xs-6" id="activeValue_'+num+'Box"><input type="text" id="activeValue_'+num+'" class="form-control" name="Post[activeValue_'+num+']"></div>' +
                        '</div>'
                );
            });
            $('#delActive').on('click',function () {
                var row = $('#postItemValue .row'),
                        num = row.length-1;
                if(num>0){
                    row[num].remove();
                }else{
                    alert('没有可删除内容')
                }
            });

            $('#formSubmit').on('click',function (e) {
                var sub = 0,
                    content = $('.ql-editor').html(),
                    tagGroup = $(".postTagBox input"),
                    post_tag = $("#postTag").find("option:selected").text();
                $('#PostContent').val(content);
                var tagArr = [],tagValue="";
                for(i =0;i<tagGroup.length;i++){
                    if($(tagGroup[i]).is(":checked")){
                        tagArr.push($(tagGroup[i]).val());
                    }
                }
                if(tagArr.length){
                    tagValue = JSON.stringify(tagArr);
                }
                $('#PostTagArr').val(tagValue);

                if(hasError('titleName'))sub=1;
                if(hasError('authorName'))sub=1;
                if(hasError('coupon_id'))sub=1;
                if(hasError('coupon_num'))sub=1;
                if(hasError('coupon_limit'))sub=1;

                if(post_tag==='折扣券'){
                    if(hasError('coupon_discount'))sub=1;
                }else if(post_tag==='代金券'){
                    if(hasError('coupon_cash'))sub=1;
                }else{
                    if(hasError('coupon_full'))sub=1;
                    if(hasError('coupon_cut'))sub=1;
                }

                for(i=0;i<$('#postItemValue .row').length - 1;i++){
                    if(hasError('activeKey_'+i))sub=1;
                    if(hasError('activeValue_'+i))sub=1;
                }


                if(sub){
                    e.preventDefault();
                }
            });


            $('#coverImg').on('click',function () {
                upType = 'cover';
                upInit()
            });
            $('#coverVideo').on('click',function () {
                upType = 'video';
                upInit()
            });
            $('#contentImg').on('click',function () {
                upType = 'content';
                upInit()
            });
            $('#postTag').change(function () {
                selectFilter($(this).val());
                changeTag();
            });

            var uploader = new plupload.Uploader({
                browse_button : ['contentImg','coverImg','coverVideo'],
                runtimes : 'html5,flash,silverlight,html4',
                url : "https://up.qbox.me/",
                flash_swf_url : "{{asset('js/plupload/Moxie.swf')}}",
                silverlight_xap_url : "{{asset('js/plupload/Moxie.xap')}}",
                unique_names : true,
                init: {
                    PostInit: function() {},
                    BeforeUpload:function(up,file){
                        uploader.setOption("multipart_params",{
                            'token': token,
                            'key': picName+ file.id
                        });
                    },
                    FilesAdded: function(up, files) {
                        plupload.each(files, function(file) {
                            if(upType === 'cover'){
                                $('#coverName').val("等待...")
                            }else if(upType === 'video'){
                                $('#videoName').val("等待...")
                            }
                        });
                    },
                    QueueChanged:function(){
                        uploader.start();
                    },
                    UploadProgress: function(up, file) {
                        if(upType === 'cover'){
                            $('#coverName').val(file.percent + "%")
                        }else if(upType === 'video'){
                            $('#videoName').val(file.percent + "%")
                        }
                        if(file.percent==100){
                            if(upType === 'cover'){
                                $('#coverName').val("即将完成")
                            }else if(upType === 'video'){
                                $('#videoName').val("即将完成")
                            }
                        }
                    },
                    FileUploaded:function(up, file, res){
                        if(upType === 'cover'){
                            $('#coverName').val("https://blhd.1demo.com/"+picName+ file.id)
                        }else if(upType === 'content'){
                            $('.ql-editor').append("<img src=\"https://blhd.1demo.com/"+picName+ file.id+"\" />")
                        }else{
                            $('#videoName').val("https://blhd.1demo.com/"+picName+ file.id)
                        }
                    },
                    UploadComplete: function(up, files) {
                        console.log('complete')
                    },
                    Error : function(up, err) {
                        console.log('fail')
                    }
                }
            });
            getToken();

            @if(isset($Post))
            $("#postLevel").val({{$Post->level}});
            $("#postStatus").val({{$Post->status}});
            $("#postTag").val({{$Post->tag}});
            $("#postXcx").val({{$Post->xcx}});

            $("#created_at").datetimepicker({format: 'yyyy-mm-dd hh:ii:ss'});
            $('#created_at').val("{{$Post->created_at}}");
            changeTag();
            @endif

            @if(isset($meta))
                var row = $('#postItemValue .row'),
                        num = row.length-1;
                while(num>0){
                    row[num].remove();
                    num--;
                }

                $("#coupon_type").val("{{$meta["coupon_type"]}}");
                @if(isset($meta["service"]))
                    activeChange('edit');
                @endif
                @if(isset($meta["service"]))
                    activeChange('edit');
                @endif

                @if(isset($meta["startCoupon"]))
                    $('#startCoupon').val("{{$meta["startCoupon"]}}");
                @endif
                @if(isset($meta["endCoupon"]))
                    $('#endCoupon').val("{{$meta["endCoupon"]}}");
                @endif
            @else
                $('#startCoupon').val("{{date("Y-m-d")}}");
                <?php $endCouponTime = strtotime('+1 week');?>
                $('#endCoupon').val("{{date("Y-m-d",$endCouponTime)}}");
            @endif

             @if(isset($meta)&&isset($meta["activeTime"]))
            $('.form_datetime').show();
            @endif

            @if(isset($tagGroup))
                var group = {{$tagGroup}},
                    tagGroup = $(".postTagBox input");
                for(var i =0;i<tagGroup.length;i++){
                    if(group.indexOf(Number($(tagGroup[i]).val()))!==-1){
                        $(tagGroup[i]).attr("checked", true);
                    }
                }
            @endif

            var filter = {!! $filter !!};
            selectFilter($("#postTag").val());

        })();
    </script>
@stop